package com.dicom.controller.front;

import ij.plugin.DICOM;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.dicom.common.Page;
import com.dicom.dao.SickDao;
import com.dicom.entity.Pic;
import com.dicom.entity.Sick;
import com.dicom.manager.PicMng;
import com.dicom.manager.SickMng;
import com.dicom.utils.ParseDicomtFileUtils;
import com.dicom.utils.ResponseUtils;

@Controller
public class SickController {

	private Logger log = LoggerFactory.getLogger(SickController.class);

	@RequestMapping(value = "/sick/list")
	public String list(Page page, ModelMap model) {
		page = sickMng.getList(page);
		model.put("page", page);
		return "list";
	}

	@RequestMapping(value = "/sick")
	public String index() {
		return "redirect:list";
	}

	@RequestMapping(value = "/sick/detail")
	public String detail(String id, ModelMap model) {
		Sick sick = sickMng.getSick(id);
		model.put("sick", sick);
		return "detail";
	}

	@RequestMapping(value = "/sick/sortPic")
	public String detail(String[] img, String sort, ModelMap model) {
		List<Pic> list = picMng.getList(img);
		String[] sorts = sort.split("\\*");
		Integer row = Integer.parseInt(sorts[0]);
		Integer col = Integer.parseInt(sorts[1]);
		model.put("list", list);
		model.put("row", row);
		model.put("col", col);
		return "dayin";
	}

	@RequestMapping(value="/uploadPic")
	public void uploadPic(HttpServletResponse response,HttpServletRequest request,@RequestParam("files") MultipartFile file){
		String uuid=UUID.randomUUID().toString();
		File dicomFile=new File(request.getSession().getServletContext()
				.getRealPath("\\resources\\front\\dicom")+"\\"+uuid+".dcm");
		try {
			file.transferTo(dicomFile);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		DICOM dicom = ParseDicomtFileUtils.parseFile(dicomFile);
		List<DICOM> dicomList=new ArrayList<DICOM>();
		dicomList.add(dicom);
        List<Sick> sicks = ParseDicomtFileUtils.getPatients(dicomList,request);
        sickDao.saveAll(sicks);
		ResponseUtils.renderJson(response, "");
	}

	@Autowired
	private SickMng sickMng;
	@Autowired
	private PicMng picMng;
	@Autowired
	private SickDao sickDao;
}
